import { loginSubmit, loginout,zhxyLogin } from '@/api/login'
import { setToken } from '@/utils/auth';
import { resetRouter } from '@/router';

const getDefaultState = () => {
  return {
    USER_INFO: !sessionStorage.getItem("userInfo") ? {} : JSON.parse(sessionStorage.getItem("userInfo")),
    TOKEN: !sessionStorage.getItem("token") ? "" : sessionStorage.getItem("token"),
    BASE_URL: !sessionStorage.getItem("baseUrl") ? "" : sessionStorage.getItem("baseUrl"),
  }
}

const state = getDefaultState()

const mutations = {
  SET_INFO: (state, info) => {
    state.USER_INFO = info
  },
  SET_TOKEN: (state, token) => {
    state.TOKEN = token
  },
  SET_BASE_URL: (state, url) => {
    state.BASE_URL = url
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginSubmit(userInfo).then(response => {
        if (response.code === 200) {
          commit('SET_TOKEN', response.result.token);
          commit('SET_INFO', response.result.userInfo);
          commit('SET_BASE_URL', response.result.baseUrl);
          setToken(response.result.token);
          sessionStorage.setItem("userInfo", JSON.stringify(response.result.userInfo));
          sessionStorage.setItem("baseUrl", response.result.baseUrl);
        }
        resolve(response)
      }).catch(Error => {
        reject(Error)
      })
    })
  },
  zhxyLogin({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
     zhxyLogin(userInfo).then(response => {
        if (response.code === 200) {
          // commit('SET_TOKEN', response.result.token);
          // commit('SET_INFO', response.result.userInfo);
          // commit('SET_BASE_URL', response.result.baseUrl);
          // setToken(response.result.token);
          // sessionStorage.setItem("userInfo", JSON.stringify(response.result.userInfo));
          // sessionStorage.setItem("baseUrl", response.result.baseUrl);
        }
        resolve(response)
      }).catch(Error => {
        reject(Error)
      })
    })
  },
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      loginout().then(() => {
        commit('SET_TOKEN', "");
        commit('SET_INFO', {});
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token")
        resetRouter();
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

